perm filename GFTYPE.WEB[MF,ALS] blob sn#764514 filedate 1984-08-12 generic text, type C, neo UTF8
COMMENT ⊗   VALID 00013 PAGES
C REC  PAGE   DESCRIPTION
C00001 00001
C00002 00002	% This program by D. R. Fuchs is not copyrighted and can be used freely.
C00005 00003	@* Introduction.
C00012 00004	@* The character set.
C00020 00005	@* Generic font file format.
C00046 00006	@* Input from binary files.
C00052 00007	@* Optional modes of output.
C00061 00008	@* The image array.
C00068 00009	@* Translation to symbolic form.
C00080 00010	@* Reading the postamble.
C00086 00011	@* The main program.
C00093 00012	@* System-dependent changes.
C00094 00013	@* Index.
C00095 ENDMK
C⊗;
% This program by D. R. Fuchs is not copyrighted and can be used freely.
% Version 0 was implemented in March 1984, before METAFONT itself was complete.
% Version 1 incorporated refinements suitable for the TRAP test (August 1984).

% Here is TeX material that gets inserted after \input webmac
\def\hang{\hangindent 3em\noindent\ignorespaces}
\def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
\font\ninerm=amr9
\let\mc=\ninerm % medium caps for names like PASCAL
\font\tenss=amss10 % for `The METAFONTbook'
\def\PASCAL{{\mc PASCAL}}
\def\ph{{\mc PASCAL-H}}
\font\logo=manfnt % font used for the METAFONT logo
\def\MF{{\logo META}\-{\logo FONT}}
\def\<#1>{$\langle#1\rangle$}
\def\section{\mathhexbox278}
\let\swap=\leftrightarrow
\def\round{\mathop{\rm round}\nolimits}

\def\(#1){} % this is used to make section names sort themselves better
\def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>

\def\title{GFtype}
\def\topofcontents{\null
	\def\titlepage{F} % include headline on the contents page
	\def\rheader{\mainfont\hfil \contentspagenumber}
	\vfill
	\centerline{\titlefont The {\ttitlefont GFtype} processor}
	\vskip 15pt
	\centerline{(Version 1.0, August 1984)}
	\vfill}
\def\botofcontents{\vfill
	\centerline{\hsize 5in\baselineskip9pt
		\vbox{\ninerm\noindent
		The preparation of this report
		was supported in part by the National Science
		Foundation under grants IST-8201926 and MCS-8300984,
		and by the System Development Foundation. `\TeX' is a
		trademark of the American Mathematical Society.}}}
\pageno=\contentspagenumber \advance\pageno by 1
@* Introduction.
The \.{GFtype} utility program reads binary generic-font (``\.{GF}'')
files that are produced by font compilers such as \MF, and converts them
into symbolic form. This program has two chief purposes: (1)~It can be used to
determine whether a \.{GF} file is valid or invalid, when diagnosing
compiler errors; and (2)~it serves as an example of a program that reads
\.{GF} files correctly, for system programmers who are developing
\.{GF}-related software.

The original version of this program was written by David R. Fuchs in
March, 1984. Donald E. Knuth made a few modifications later that year as
\MF\ was taking shape.
@↑Fuchs, David Raymond@>
@↑Knuth, Donald Ervin@>

The |banner| string defined here should be changed whenever \.{GFtype}
gets modified.

@d banner=='This is GFtype, Version 1.0' {printed when the program starts}

@ This program is written in standard \PASCAL, except where it is
necessary to use extensions; for example, one extension is to use a
default |case| as in \.{TANGLE}, \.{WEAVE}, etc.  All places where
nonstandard constructions are used have been listed in the index under
``system dependencies.''
@!@↑system dependencies@>

@d othercases == others: {default for cases not listed explicitly}
@d endcases == @+end {follows the default case in an extended |case| statement}
@f othercases == else
@f endcases == end

@ The binary input comes from |gf_file|, and the symbolic output is written
on \PASCAL's standard |output| file. The term |print| is used instead of
|write| when this program writes on |output|, so that all such output
could easily be redirected if desired.

@d print(#)==write(#)
@d print_ln(#)==write_ln(#)
@d print_nl==write_ln

@p program GF_type(@!gf_file,@!output);
label @<Labels in the outer block@>@/
const @<Constants in the outer block@>@/
type @<Types in the outer block@>@/
var @<Globals in the outer block@>@/
procedure initialize; {this procedure gets things started properly}
	var i:integer; {loop index for initializations}
	begin print_ln(banner);@/
	@<Set initial values@>@/
	end;

@ If the program has to stop prematurely, it goes to the
`|final_end|'.

@d final_end=9999 {label for the end of it all}

@<Labels...@>=final_end;

@ The following parameters can be changed at compile time to extend or
reduce \.{GFtype}'s capacity.

The total number of bits in the main |image_array| will be
$$\hbox{|top_pixel+1-bot_pixel| $\times$ |right_pixel+1-left_pixel|}.$$
(\MF's full pixel range is rarely implemented, because it would require
8~megabytes of memory.)

@<Constants...@>=
@!terminal_line_length=150; {maximum number of characters input in a single
	line of input from the terminal}
@!line_length=79; {\\{xxx} strings will not produce lines longer than this}
@!top_pixel=69; {upper boundary of pixel image of character}
@!bot_pixel=-10; {lower boundary, ditto}
@!left_pixel=-10; {left boundary, ditto}
@!right_pixel=69; {guess what}

@ Here are some macros for common programming idioms.

@d incr(#) == #←#+1 {increase a variable by unity}
@d decr(#) == #←#-1 {decrease a variable by unity}
@d negate(#) == #←-# {change the sign of a variable}

@ If the \.{GF} file is badly malformed, the whole process must be aborted;
\.{GFtype} will give up, after issuing an error message about the symptoms
that were noticed.

Such errors might be discovered inside of subroutines inside of subroutines,
so a procedure called |jump_out| has been introduced. This procedure, which
simply transfers control to the label |final_end| at the end of the program,
contains the only non-local |goto| statement in \.{GFtype}.
@↑system dependencies@>

@d abort(#)==begin print(' ',#); jump_out;
		end
@d bad_gf(#)==abort('Bad GF file: ',#,'!')
@.Bad GF file@>

@p procedure jump_out;
begin goto final_end;
end;
@* The character set.
Like all programs written with the  \.{WEB} system, \.{GFtype} can be
used with any character set. But it uses ASCII code internally, because
the programming for portable input-output is easier when a fixed internal
code is used.

The next few sections of \.{GFtype} have therefore been copied from the
analogous ones in the \.{WEB} system routines. They have been considerably
simplified, since \.{GFtype} need not deal with the controversial
ASCII codes less than @'40. If such codes appear in the \.{GF} file,
they will be printed as question marks.

@<Types...@>=
@!ASCII_code=" ".."~"; {a subrange of the integers}

@ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
character sets were common, so it did not make provision for lower case
letters. Nowadays, of course, we need to deal with both upper and lower case
alphabets in a convenient way, especially in a program like \.{GFtype}.
So we shall assume that the \PASCAL\ system being used for \.{GFtype}
has a character set containing at least the standard visible characters
of ASCII code (|"!"| through |"~"|).

Some \PASCAL\ compilers use the original name |char| for the data type
associated with the characters in text files, while other \PASCAL s
consider |char| to be a 64-element subrange of a larger data type that has
some other name.  In order to accommodate this difference, we shall use
the name |text_char| to stand for the data type of the characters in the
output file.  We shall also assume that |text_char| consists of
the elements |chr(first_text_char)| through |chr(last_text_char)|,
inclusive. The following definitions should be adjusted if necessary.
@↑system dependencies@>

@d text_char == char {the data type of characters in text files}
@d first_text_char=0 {ordinal number of the smallest element of |text_char|}
@d last_text_char=127 {ordinal number of the largest element of |text_char|}

@<Types...@>=
@!text_file=packed file of text_char;

@ The \.{GFtype} processor converts between ASCII code and
the user's external character set by means of arrays |xord| and |xchr|
that are analogous to \PASCAL's |ord| and |chr| functions.

@<Globals...@>=
@!xord: array [text_char] of ASCII_code;
	{specifies conversion of input characters}
@!xchr: array [0..255] of text_char;
	{specifies conversion of output characters}

@ Under our assumption that the visible characters of standard ASCII are
all present, the following assignment statements initialize the
|xchr| array properly, without needing any system-dependent changes.

@<Set init...@>=
for i←0 to @'37 do xchr[i]←'?';
xchr[@'40]←' ';
xchr[@'41]←'!';
xchr[@'42]←'"';
xchr[@'43]←'#';
xchr[@'44]←'$';
xchr[@'45]←'%';
xchr[@'46]←'&';
xchr[@'47]←'''';@/
xchr[@'50]←'(';
xchr[@'51]←')';
xchr[@'52]←'*';
xchr[@'53]←'+';
xchr[@'54]←',';
xchr[@'55]←'-';
xchr[@'56]←'.';
xchr[@'57]←'/';@/
xchr[@'60]←'0';
xchr[@'61]←'1';
xchr[@'62]←'2';
xchr[@'63]←'3';
xchr[@'64]←'4';
xchr[@'65]←'5';
xchr[@'66]←'6';
xchr[@'67]←'7';@/
xchr[@'70]←'8';
xchr[@'71]←'9';
xchr[@'72]←':';
xchr[@'73]←';';
xchr[@'74]←'<';
xchr[@'75]←'=';
xchr[@'76]←'>';
xchr[@'77]←'?';@/
xchr[@'100]←'@@';
xchr[@'101]←'A';
xchr[@'102]←'B';
xchr[@'103]←'C';
xchr[@'104]←'D';
xchr[@'105]←'E';
xchr[@'106]←'F';
xchr[@'107]←'G';@/
xchr[@'110]←'H';
xchr[@'111]←'I';
xchr[@'112]←'J';
xchr[@'113]←'K';
xchr[@'114]←'L';
xchr[@'115]←'M';
xchr[@'116]←'N';
xchr[@'117]←'O';@/
xchr[@'120]←'P';
xchr[@'121]←'Q';
xchr[@'122]←'R';
xchr[@'123]←'S';
xchr[@'124]←'T';
xchr[@'125]←'U';
xchr[@'126]←'V';
xchr[@'127]←'W';@/
xchr[@'130]←'X';
xchr[@'131]←'Y';
xchr[@'132]←'Z';
xchr[@'133]←'[';
xchr[@'134]←'\';
xchr[@'135]←']';
xchr[@'136]←'↑';
xchr[@'137]←'_';@/
xchr[@'140]←'`';
xchr[@'141]←'a';
xchr[@'142]←'b';
xchr[@'143]←'c';
xchr[@'144]←'d';
xchr[@'145]←'e';
xchr[@'146]←'f';
xchr[@'147]←'g';@/
xchr[@'150]←'h';
xchr[@'151]←'i';
xchr[@'152]←'j';
xchr[@'153]←'k';
xchr[@'154]←'l';
xchr[@'155]←'m';
xchr[@'156]←'n';
xchr[@'157]←'o';@/
xchr[@'160]←'p';
xchr[@'161]←'q';
xchr[@'162]←'r';
xchr[@'163]←'s';
xchr[@'164]←'t';
xchr[@'165]←'u';
xchr[@'166]←'v';
xchr[@'167]←'w';@/
xchr[@'170]←'x';
xchr[@'171]←'y';
xchr[@'172]←'z';
xchr[@'173]←'{';
xchr[@'174]←'|';
xchr[@'175]←'}';
xchr[@'176]←'~';
for i←@'177 to 255 do xchr[i]←'?';

@ The following system-independent code makes the |xord| array contain a
suitable inverse to the information in |xchr|.

@<Set init...@>=
for i←first_text_char to last_text_char do xord[chr(i)]←@'40;
for i←" " to "~" do xord[xchr[i]]←i;
@* Generic font file format.
The most important output produced by a production run of \MF\ is the
``generic font'' (\.{GF}) file that specifies the bit patterns of the
characters that have been drawn. The term {\sl generic\/} indicates that
this file format doesn't match the conventions of any name-brand manufacturer;
but it is easy to convert \.{GF} files to the special format required by
almost all digital phototypesetting equipment. There's a strong analogy
between the \.{DVI} files written by \TeX\ and the \.{GF} files written
by \MF; and, in fact, the file formats have a lot in common.
It is therefore not surprising that \.{GFtype} is identical in many
respects to the \.{DVItype} program.

A \.{GF} file is a stream of 8-bit bytes that may be
regarded as a series of commands in a machine-like language. The first
byte of each command is the operation code, and this code is followed by
zero or more bytes that provide parameters to the command. The parameters
themselves may consist of several consecutive bytes; for example, the
`|boc|' (beginning of character) command has seven parameters, each of
which is four bytes long. Parameters are usually regarded as nonnegative
integers; but four-byte-long parameters can be either positive or
negative, hence they range in value from $-2↑{31}$ to $2↑{31}-1$.
As in \.{TFM} files, numbers that occupy
more than one byte position appear in BigEndian order,
and negative numbers appear in two's complement notation.

A \.{GF} file consists of a ``preamble,'' followed by a sequence of one or
more ``characters,'' followed by a ``postamble.'' The preamble is simply a
|pre| command, with its parameters that introduce the file; this must come
first.  Each ``character'' consists of a |boc| command, followed by any
number of other commands that specify ``black'' pixels,
followed by an |eoc| command. The characters appear in the order that \MF\
generated them. If we ignore no-op commands (which are allowed between any
two commands in the file), each |eoc| command is immediately followed by a
|boc| command, or by a |post| command; in the latter case, there are no
more characters in the file, and the remaining bytes form the postamble.
Further details about the postamble will be explained later.

Some parameters in \.{GF} commands are ``pointers.'' These are four-byte
quantities that give the location number of some other byte in the file;
the first file byte is number~0, then comes number~1, and so on.

@ The \.{GF} format is intended to be both compact and easily interpreted
by a machine. Compactness is achieved by making most of the information
relative instead of absolute. When a \.{GF}-reading program reads the
commands for a character, it keeps track of several quantities: (a)~the current
row number,~|y|; (b)~the current column number,~|x|; and (c)~the current
starting-column number,~|z|. These are 32-bit signed integers, although
most actual font formats produced from \.{GF} files will need to curtail
this vast range because of practical limitations. (\MF\ output will never
allow $\vert x\vert$, $\vert y\vert$, or $\vert z\vert$ to exceed 4095,
but the \.{GF} format tries to be more general.)

How do \.{GF}'s row and column numbers correspond to the conventions
of \TeX\ and \MF? Well, the ``reference point'' of a character, in \TeX's
view, is considered to be at the lower left corner of the pixel in row~0
and column~0. This point is the intersection of the baseline with the left
edge of the type; it corresponds to location $(0,0)$ in \MF\ programs.
Thus the pixel in row~0 and column~0 is \MF's unit square, comprising the
region of the plane whose coordinates both lie between 0 and~1. Negative
values of~|y| correspond to rows of pixels {\sl below\/} the baseline.
Negative values of~|x| correspond to columns of pixels {\sl left\/} of
the reference point.

Besides |x|, |y|, and |z|, there's also a fourth aspect of the current
state, namely the @!|paint_switch|, which is always either \\{black} or
\\{white}. Each \\{paint} command advances |x| by a specified amount~|d|,
and blackens the intervening pixels if |paint_switch=black|; then
the |paint_switch| changes to the opposite state. \.{GF}'s commands are
designed so that |x| will never decrease within a row, and |y| will never
increase within a character; hence there is no way to whiten a pixel that
has been blackened.

@ Here is a list of all the commands that may appear in a \.{GF} file. Each
command is specified by its symbolic name (e.g., |boc|), its opcode byte
(e.g., 67), and its parameters (if any). The parameters are followed
by a bracketed number telling how many bytes they occupy; for example,
`|d[2]|' means that parameter |d| is two bytes long.

\yskip\hang|paint_0| 0. This is a \\{paint} command with |d=0|; it does
nothing but change the |paint_switch| from \\{black} to \\{white} or vice~versa.

\yskip\hang\\{paint\_1} through \\{paint\_63} (opcodes 1 to 63).
These are \\{paint} commands with |d=1| to~63, defined as follows: If
|paint_switch=black|, blacken |d|~pixels of the current row~|y|,
in columns |x| through |x+d-1| inclusive. Then, in any case,
complement the |paint_switch| and advance |x| by~|d|.

\yskip\hang|paint1| 64 |d[1]|. This is a \\{paint} command with a specified
value of~|d|; \MF\ uses it to paint when |64≤d<256|.

\yskip\hang|@!paint2| 65 |d[2]|. Same as |paint1|, but |d|~can be as high
as~65535.

\yskip\hang|@!paint3| 66 |d[3]|. Same as |paint1|, but |d|~can be as high
as $2↑{24}-1$. \MF\ never needs this command, and it is hard to imagine
anybody making practical use of it; surely a more compact encoding will be
desirable when characters can be this large. But the command is there,
anyway, just in case.

\yskip\hang|boc| 67 |c[4]| |p[4]| |min_x[4]| |max_x[4]| |min_y[4]|
|max_y[4]| |z[4]|. Beginning of a character:  Here |c| is the character
code, and |p| points to the previous |boc| command (if any) for characters
having this code number modulo 256.  (The pointer |p| is |-1| if there was
no prior character with an equivalent code.) All $x$-coordinates of painted
pixels in the character that follows will be |≥min_x| and |≤max_x|; all
$y$-coordinates of painted pixels will be |≥min_y| and |≤max_y|. Finally,
|z|~is the leftmost potentially black column in row |max_y|; it satisfies
|min_x≤z≤max_x|. When a \.{GF}-reading program sees a |boc|, it can use
|min_x|, |max_x|, |min_y|, and |max_y| to initialize the bounds of an
array. Then it sets |y←max_y|, |paint_switch←black|, and initializes its
|x| and |z| registers both to the stated value of~|z|.

\yskip\hang|eoc| 68. End of character: All pixels blackened so far
constitute the pattern for this character. In particular, a completely
blank character might have |eoc| immediately following |boc|.

\yskip\hang|skip1| 69 |m[1]|. Decrease |y| by |m+1|, set |x←z|, and set
|paint_switch←black|. This is a way to produce |m| all-white rows.

\yskip\hang|skip2| 70 |m[2]|. Same as |skip1|, but |m| can be as large
as 65535.

\yskip\hang|skip3| 71 |m[3]|. Same as |skip1|, but |m| can be as large
as $2↑{24}-1$. \MF\ obviously never needs this command.

\yskip\hang|new_row| 72 |u[4]|. Decrease |y| by 1 and set |z←z+u|; then set
|x←z| and |paint_switch←black|. (It's a general way to finish one row
and begin another.)

\yskip\hang|left_z_83| through |@!left_z_1| (opcodes 73 to 155). Same as
|new_row|, with |u=-83| through |-1|, respectively.

\yskip\hang|right_z_0| 156. Same as |skip1| with |m=0| or |new_row| with
|u=0|.

\yskip\hang|right_z_1| through |right_z_83| (opcodes 157 to 239). Same as
|new_row|, with |u=+1| through |+83|, respectively. \MF\ generates a
|new_row| command only when $\vert u\vert>83$.

\yskip\hang|nop| 240. No operation, do nothing. Any number of |nop|'s
may occur between \.{GF} commands, but a |nop| cannot be inserted between
a command and its parameters or between two parameters.

\yskip\hang|xxx1| 241 |k[1]| |x[k]|. This command is undefined in
general; it functions as a $(k+2)$-byte |nop| unless special \.{GF}-reading
programs are being used. \MF\ generates \\{xxx} commands when encountering
a \&{special} string; this occurs in the \.{GF} file only between
characters, after the preamble, and before the postamble. However,
\\{xxx} commands might appear anywhere in \.{GF} files generated by other
processors. It is recommended that |x| be a string having the form of a
keyword followed by possible parameters relevant to that keyword.

\yskip\hang|@!xxx2| 242 |k[2]| |x[k]|. Like |xxx1|, but |0≤k<65536|.

\yskip\hang|xxx3| 243 |k[3]| |x[k]|. Like |xxx1|, but |0≤k<@t$2↑{24}$@>|.
\MF\ uses this when sending a \&{special} string whose length exceeds~255.

\yskip\hang|@!xxx4| 244 |k[4]| |x[k]|. Like |xxx1|, but |k| can be
ridiculously large; |k| mustn't be negative.

\yskip\hang|yyy| 245 |n[4]|. This command is undefined in general;
it functions as a 5-byte |nop| unless special \.{GF}-reading programs
are being used. \MF\ puts scaled numbers into |yyy|'s, as a
result of \&{numspecial} commands; the intent is to provide numeric
parameters to \\{xxx} commands that immediately precede.

\yskip\hang|char_loc| 246 |c[1]| |v[4]| |w[4]| |p[4]|.
This command will appear only in the postamble, which will be explained shortly.

\yskip\hang|pre| 247 |i[1]| |k[1]| |x[k]|.
Beginning of the preamble; this must come at the very beginning of the
file. Parameter |i| is an identifying number for \.{GF} format, currently
129. The other information is merely commentary; it is not given
special interpretation like \\{xxx} commands are. (Note that \\{xxx}
commands may immediately follow the preamble, before the first |boc|.)

\yskip\hang|post| 248. Beginning of the postamble, see below.

\yskip\hang|post_post| 249. Ending of the postamble, see below.

\yskip\noindent Commands 250--255 are undefined at the present time.

@d gf_id_byte=129 {identifies the kind of \.{GF} files described here}

@ Here are the opcodes \.{GFtype} actually refers to.

@d paint_0=0 {beginning of the \\{paint} commands}
@d paint1=64 {move right a given number of columns, then
	black${}\swap{}$white}
@d boc=67 {beginning of a character}
@d eoc=68 {end of a character}
@d skip1=69 {skip over blank rows}
@d new_row=72 {move down one row and adjust |z|}
@d right_z_0=156 {base of shorthand |new_row| commands}
@d right_z_1=157 {the next shorthand |new_row| command}
@d right_z_83=239 {the last shorthand |new_row| command}
@d left_z_83=73 {the first shorthand |new_row| command}
@d nop=240 {no operation}
@d xxx1=241 {for \&{special} strings}
@d yyy=245 {for \&{numspecial} numbers}
@d char_loc=246 {character locators in the postamble}
@d pre=247 {preamble}
@d post=248 {postamble beginning}
@d post_post=249 {postamble ending}
@d undefined_commands==250,251,252,253,254,255

@ The last character in a \.{GF} file is followed by `|post|'; this command
introduces the postamble, which summarizes important facts that \MF\ has
accumulated. The postamble has the form
$$\vbox{\halign{\hbox{#\hfil}\cr
	|post| |p[4]| |@!ds[4]| |@!cs[4]| |@!hppp[4]| |@!vppp[4]|
	 |@!min_x[4]| |@!max_x[4]| |@!min_y[4]| |@!max_y[4]|\cr
	$\langle\,$character locators$\,\rangle$\cr
	|post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
Here |p| is a pointer to the byte following the final |eoc| in the file
(or to the byte following the preamble, if there are no characters);
it can be used to locate the beginning of \\{xxx} commands
that might have preceded the postamble. The |ds| and |cs| parameters
give the design size and check sum, respectively, which are exactly the
values put into the header of any \.{TFM} file that corresponds to this
\.{GF} file. Parameters |hppp| and |vppp| are the ratios of
pixels per point, horizontally and vertically, expressed as |scaled| integers
(i.e., multiplied by $2↑{16}$); they can be used to correlate the font
with specific device resolutions, magnifications, and ``at sizes.''  Then
come |min_x|, |max_x|, |min_y|, and |max_y|, which bound the values that |x|
and~|y| assume in all painted pixels of the characters in this \.{GF} file.

@ Character locators are introduced by |char_loc| commands,
which contain a character residue~|c|, a character device width~|v|,
a character width~|w|, and a pointer~|p|
to the beginning of that character. (If two or more characters have the
same code~|c| modulo 256, only the last will be indicated; the others can be
located by following backpointers. Characters whose codes differ by a
multiple of 256 are assumed to share the same font metric information,
hence the \.{TFM} file contains only residues of character codes modulo~256.
This convention is intended for oriental languages, when there are many
character shapes but few distinct widths.)
@↑oriental characters@>@↑Chinese characters@>@↑Japanese characters@>

The character device width~|v| is the value of \MF's \&{chardw} parameter,
rounded to the nearest integer, i.e., the number of pixels that the font
designer wishes the character to occupy when it is typeset within a word.

The character width~|w| duplicates the information in the \.{TFM} file; it
is $2↑{24}$ times the ratio of the true width to the font's design size.

The backpointer |p| points to the character's |boc|, or to the first of
a sequence of consecutive |nop| or \\{xxx} or |yyy| commands that
immediately precede the |boc|, if such commands exist; such ``special''
commands essentially belong to the characters, while the special commands
after the final character belong to the postamble (i.e., to the font
as a whole). This convention about |p| applies also to the backpointers
in |boc| commands, even though it wasn't explained in the description
of~|boc|.

@ The last part of the postamble, following the |post_post| byte that
signifies the end of the character locators, contains |q|, a pointer to the
|post| command that started the postamble.  An identification byte, |i|,
comes next; this currently equals~129, as in the preamble.

The |i| byte is followed by four or more bytes that are all equal to
the decimal number 223 (i.e., @'337 in octal). \MF\ puts out four to seven of
these trailing bytes, until the total length of the file is a multiple of
four bytes, since this works out best on machines that pack four bytes per
word; but any number of 223's is allowed, as long as there are at least four
of them. In effect, 223 is a sort of signature that is added at the very end.
@↑Fuchs, David Raymond@>

This curious way to finish off a \.{GF} file makes it feasible for
\.{GF}-reading programs to find the postamble first, on most computers,
even though \MF\ wants to write the postamble last. Most operating
systems permit random access to individual words or bytes of a file, so
the \.{GF} reader can start at the end and skip backwards over the 223's
until finding the identification byte. Then it can back up four bytes, read
|q|, and move to byte |q| of the file. This byte should, of course,
contain the value 248 (|post|); now the postamble can be read, so the
\.{GF} reader can discover all the information needed for individual characters.

Unfortunately, however, standard \PASCAL\ does not include the ability to
@↑system dependencies@>
access a random position in a file, or even to determine the length of a file.
Almost all systems nowadays provide the necessary capabilities, so \.{GF}
format has been designed to work most efficiently with modern operating systems.
But if \.{GF} files have to be processed under the restrictions of standard
\PASCAL, one can simply read them from front to back. This will
be adequate for most applications. However, the postamble-first approach
would facilitate a program that merges two \.{GF} files, replacing data
from one that is overridden by corresponding data in the other.
@* Input from binary files.
We have seen that a \.{GF} file is a sequence of 8-bit bytes. The bytes
appear physically in what is called a `|packed file of 0..255|'
in \PASCAL\ lingo.

Packing is system dependent, and many \PASCAL\ systems fail to implement
such files in a sensible way (at least, from the viewpoint of producing
good production software).  For example, some systems treat all
byte-oriented files as text, looking for end-of-line marks and such
things. Therefore some system-dependent code is often needed to deal with
binary files, even though most of the program in this section of
\.{GFtype} is written in standard \PASCAL.
@↑system dependencies@>

We shall stick to simple \PASCAL\ in this program, for reasons of clarity,
even if such simplicity is sometimes unrealistic.

@<Types...@>=
@!eight_bits=0..255; {unsigned one-byte quantity}
@!byte_file=packed file of eight_bits; {files that contain binary data}

@ The program deals with one binary file variable: |gf_file| is the main
input file that we are translating into symbolic form.

@<Glob...@>=
@!gf_file:byte_file; {the stuff we are \.{GF}typing}

@ To prepare this file for input, we |reset| it.

@p procedure open_gf_file; {prepares to read packed bytes in |gf_file|}
begin reset(gf_file);
cur_loc←0;
end;

@ If you looked carefully at the preceding code, you probably asked,
``What is |cur_loc|?'' Good question. It's a global variable that holds
the number of the byte about to be read next from |gf_file|.

@<Glob...@>=
@!cur_loc:integer; {where we are about to look, in |gf_file|}

@ We shall use a set of simple functions to read the next byte or
bytes from |gf_file|. There are four possibilities, each of which is
treated as a separate function in order to minimize the overhead for
subroutine calls.
@↑system dependencies@>

@p function get_byte:integer; {returns the next byte, unsigned}
var b:eight_bits;
begin if eof(gf_file) then get_byte←0
else	begin read(gf_file,b); incr(cur_loc); get_byte←b;
	end;
end;
@#
function get_two_bytes:integer; {returns the next two bytes, unsigned}
var a,@!b:eight_bits;
begin read(gf_file,a); read(gf_file,b);
cur_loc←cur_loc+2;
get_two_bytes←a*256+b;
end;
@#
function get_three_bytes:integer; {returns the next three bytes, unsigned}
var a,@!b,@!c:eight_bits;
begin read(gf_file,a); read(gf_file,b); read(gf_file,c);
cur_loc←cur_loc+3;
get_three_bytes←(a*256+b)*256+c;
end;
@#
function signed_quad:integer; {returns the next four bytes, signed}
var a,@!b,@!c,@!d:eight_bits;
begin read(gf_file,a); read(gf_file,b); read(gf_file,c); read(gf_file,d);
cur_loc←cur_loc+4;
if a<128 then signed_quad←((a*256+b)*256+c)*256+d
else signed_quad←(((a-256)*256+b)*256+c)*256+d;
end;
@* Optional modes of output.
\.{GFtype} will print different quantities of information based on some
options that the user must specify: We set |wants_mnemonics| if the
user wants to see a mnemonic dump of the \.{GF} file; and we set
|wants_pixels| if the user wants to see a pixel image of each
character.

When \.{GFtype} begins, it engages the user in a brief dialog so that the
options will be specified. This part of \.{GFtype} requires nonstandard
\PASCAL\ constructions to handle the online interaction; so it may be
preferable in some cases to omit the dialog and simply to stick to the
default options (|wants_mnemonics=wants_pixels=true|).
On other hand, the
system-dependent routines that are needed are not complicated, so it will
not be terribly difficult to introduce them.
@↑system dependencies@>

@<Glob...@>=
@!wants_mnemonics: boolean; {controls mnemonic output}
@!wants_pixels: boolean; {controls pixel output}

@ @<Set init...@>=
wants_mnemonics←true; wants_pixels←true;

@ The |input_ln| routine waits for the user to type a line at his or her
terminal; then it puts ASCII-code equivalents for the characters on that line
into the |buffer| array. The |term_in| file is used for terminal input,
and |term_out| for terminal output.
@↑system dependencies@>

@<Glob...@>=
@!buffer:array[0..terminal_line_length] of ASCII_code;
@!term_in:text_file; {the terminal, considered as an input file}
@!term_out:text_file; {the terminal, considered as an output file}

@ Since the terminal is being used for both input and output, some systems
need a special routine to make sure that the user can see a prompt message
before waiting for input based on that message. (Otherwise the message
may just be sitting in a hidden buffer somewhere, and the user will have
no idea what the program is waiting for.) We shall invoke a system-dependent
subroutine |update_terminal| in order to avoid this problem.
@↑system dependencies@>

@d update_terminal == break(term_out) {empty the terminal output buffer}

@ During the dialog, extensions of \.{GFtype} might treat the first blank space in a
line as the end of that line. Therefore |input_ln| makes sure that there
is always at least one blank space in |buffer|.

(This routine is more complex than the present implementation needs, but
it has been copied from \.{DVItype} so that system-dependent changes that
worked before will work again.)
@↑system dependencies@>

@p procedure input_ln; {inputs a line from the terminal}
var k:0..terminal_line_length;
begin update_terminal; reset(term_in);
if eoln(term_in) then read_ln(term_in);
k←0;
while (k<terminal_line_length)∧ not eoln(term_in) do
	begin buffer[k]←xord[term_in↑]; incr(k); get(term_in);
	end;
buffer[k]←" ";
end;

@ This is humdrum.

@p function lower_casify(@!c:ASCII_code):ASCII_code;
begin
if (c≥"A") and (c≤"Z") then lower_casify←c+"a"-"A"
else lower_casify←c;
end;

@ The selected options are put into global variables by the |dialog|
procedure, which is called just as \.{GFtype} begins.
@↑system dependencies@>

@p procedure dialog;
label 1,2;
var k:integer; {loop variable}
begin rewrite(term_out); {prepare the terminal for output}
write_ln(term_out,banner);@/
@<Determine whether the user |wants_mnemonics|@>;
@<Determine whether the user |wants_pixels|@>;
@<Print all the selected options@>;
end;

@ @<Determine whether the user |wants_mnemonics|@>=
1: write(term_out,'Mnemonic output? (default=yes, ? for help): ');
@.Mnemonic output?@>
wants_mnemonics←true; input_ln;
buffer[0]←lower_casify(buffer[0]);
if buffer[0]≠"?" then
	wants_mnemonics←(buffer[0]="y")∨(buffer[0]="1")∨(buffer[0]="t")
		∨(buffer[0]=" ")
else	begin write(term_out,'Type Y for complete listing,');
	write_ln(term_out,' N for errors/images only.');
	goto 1;
	end

@ @<Determine whether the user |wants_pixels|@>=
2: write(term_out,'Pixel output? (default=yes, ? for help): ');
@.Pixel output?@>
wants_pixels←true; input_ln;
buffer[0]←lower_casify(buffer[0]);
if buffer[0]≠"?" then
	wants_pixels←(buffer[0]="y")∨(buffer[0]="1")∨(buffer[0]="t")
		∨(buffer[0]=" ")
else	begin write(term_out,'Type Y to list characters pictorially');
	write_ln(term_out,' with *''s, N to omit this option.');
	goto 2;
	end

@ After the dialog is over, we print the options so that the user
can see what \.{GFtype} thought was specified.

@<Print all the selected options@>=
print('Options selected: Mnemonic output = ');
@.Options selected@>
if wants_mnemonics then print('true')@+else print('false');
print('; pixel output = ');
if wants_pixels then print('true')@+else print('false');
print_ln('.')
@* The image array.
The definition of \.{GF} files refers to three registers,
$(x,y,z)$, which hold integer row and column numbers.  We also
need to remember |paint_switch|, whose value is either |black|
or |white|.

@<Glob...@>=
@!x,@!y,@!z:integer; {current state values}
@!paint_switch: pixel;

@ We'll need a big array of pixels to hold the character image.  Each
pixel should be represented as a single bit in order to save space.
Some systems may prefer the following definitions, while others
may do better using the |boolean| type and boolean constants.
@↑system dependencies@>

@d white=0 {could also be |false|}
@d black=1 {could also be |true|}

@<Types...@>=
@!pixel=white..black; {could also be |boolean|}

@ In order to allow different systems to change the |image| array easily from
row-major order to column-major order (or vice versa), or to transpose it top
and bottom or left and right, we declare and access it as follows.
@↑system dependencies@>

@d image==image_array[y,x]

@<Glob...@>=
@!image_array:
	packed array [bot_pixel..top_pixel,left_pixel..right_pixel] of pixel;

@ The values of |min_x|, |max_x|, |min_y|, and |max_y| are set up to
define a rectangular subarray that will be used for the pixels of the
current character, based on the character boundaries stated in a
|boc| command. We truncate the stated bounds, if they are outside
the limits of |image_array|; then we clear the subarray to all |white|.

(There may be a faster way to clear a subarray on particular systems,
using nonstandard extensions of \PASCAL.)
@↑system dependencies@>

@<Clear the image@>=
begin min_x←min_x_stated;@+if min_x<left_pixel then min_x←left_pixel;
max_x←max_x_stated;@+if max_x>right_pixel then max_x←right_pixel;
min_y←min_y_stated;@+if min_y<bot_pixel then min_y←bot_pixel;
max_y←max_y_stated;@+if max_y>top_pixel then max_y←top_pixel;
y←min_y;
while y≤max_y do
	begin x←min_x;
	while x≤max_x do
		begin image←white;incr(x);
		end;
	incr(y);
	end;
end

@ As we paint the pixels of a character, we will record its actual
boundaries in variables |min_x_observed|, |max_x_observed|, etc.
Then the following routine will be called on to output the image,
using blanks for |white| and asterisks for |black|. Blanks are
emitted only when they are followed by nonblanks, in order to conserve
space in the output. Further compaction could be achieved on many
systems by using tab marks.
@↑system dependencies@>

An integer variable |n| will be declared for use in counting blanks.

@<Print the image@>=
begin @<Compare the subarray boundaries with the observed boundaries@>;
y←max_y;
while y≥min_y do
	begin x←min_x; n←0;
	while x≤max_x do
		begin if image=white then incr(n)
		else	begin while n>0 do
				begin print(' '); decr(n);
				end;
			print('*');
			end;
		incr(x);
		end;
	print_nl; decr(y);
	end;
end

@ @<Glob...@>=
@!min_x, @!max_x, @!min_y, @!max_y: integer; {bounds of the current subarray}
@!min_x_stated, @!max_x_stated, @!min_y_stated, @!max_y_stated: integer;
	{bounds stated in the \.{GF} file}
@!min_x_observed,@!max_x_observed,@!min_y_observed,@!max_y_observed: integer;
	{bounds actually observed when painting}
@!min_x_overall, @!max_x_overall, @!min_y_overall, @!max_y_overall: integer;
	{bounds observed in the entire file so far}

@ If the given character is substantially smaller than the |boc|
command predicted, we don't want to bother to output rows and columns
that are all blank.

@<Compare the subarray boundaries with the observed boundaries@>=
if (max_x<max_x_observed)∨(min_x>min_x_observed)∨@|
	(max_y<max_y_observed)∨(min_y>min_y_observed) then
	print_ln('(The character is too large to be displayed in full.)');
@.The character is too large...@>
if max_y>max_y_observed then max_y←max_y_observed;
if min_y<min_y_observed then min_y←min_y_observed;
if max_x>max_x_observed then max_x←max_x_observed;
if min_x<min_x_observed then min_x←min_x_observed;
print_ln('Character image, with upper left corner at (',min_x:1,
	',',max_y+1:1,'):')
@* Translation to symbolic form.
The main work of \.{GFtype} is accomplished by the |do_char| procedure,
which produces the output for an entire character, assuming that the |boc|
command for that page has already been processed. This procedure is
essentially an interpretive routine that reads and acts on the \.{GF}
commands.

@ We steal the following routine from \MF.

@d unity == @'200000 {$2↑{16}$, represents 1.00000}

@p procedure print_scaled(@!s:integer);
	{prints a scaled number, rounded to five digits}
var @!delta:integer; {amount of allowable inaccuracy}
begin if s<0 then
	begin print('-'); negate(s); {print the sign, if negative}
	end;
print(s div unity:1); {print the integer part}
s←10*(s mod unity)+5;
if s≠5 then
	begin delta←10; print('.');
	repeat if delta>unity then
		s←s+@'100000-(delta div 2); {round the final digit}
	print(chr(ord('0')+(s div unity))); s←10*(s mod unity); delta←delta*10;
	until s≤delta;
	end;
end;

@ Let's keep track of how many characters are in the font, and the
locations of where each one occured in the file.

@<Glob...@>=
@!total_chars:integer; {the total number of characters seen so far}
@!char_ptr: array[0..255] of integer; {correct character location pointer}
@!gf_prev_ptr: integer; {|char_ptr| for next character}
@!character_code: integer; {current character number}

@ @<Set init...@>=
for i←0 to 255 do char_ptr[i]←-1; {mark characters as not being in the file}
total_chars←0;

@ Before we get into the details of |do_char|, it is convenient to
consider a simpler routine that computes the first parameter of each
opcode.

@d three_cases(#)==#,#+1,#+2
@d four_cases(#)==#,#+1,#+2,#+3
@d eight_cases(#)==four_cases(#),four_cases(#+4)
@d nine_cases(#)==eight_cases(#),#+8
@d sixteen_cases(#)==eight_cases(#),eight_cases(#+8)
@d nineteen_cases(#)==nine_cases(#),nine_cases(#+9),#+18
@d thirty_two_cases(#)==sixteen_cases(#),sixteen_cases(#+16)
@d sixty_four_cases(#)==thirty_two_cases(#),thirty_two_cases(#+32)
@d eighty_three_cases(#)==sixty_four_cases(#),nineteen_cases(#+64)

@p function first_par(o:eight_bits):integer;
begin case o of
sixty_four_cases(paint_0): first_par←o-paint_0;
paint1,skip1,char_loc,xxx1: first_par←get_byte;
paint1+1,skip1+1,xxx1+1: first_par←get_two_bytes;
paint1+2,skip1+2,xxx1+2: first_par←get_three_bytes;
new_row,xxx1+3,yyy: first_par←signed_quad;
nop,boc,eoc,pre,post,post_post,undefined_commands: first_par←0;
eighty_three_cases(left_z_83), right_z_0,
	eighty_three_cases(right_z_1): first_par←o-right_z_0;
end;
end;

@ Strictly speaking, the |do_char| procedure is really a function with
side effects, not a `\&{procedure}'\thinspace; it returns the value |false|
if \.{GFtype} should be aborted because of some unusual happening. The
subroutine is organized as a typical interpreter, with a multiway branch
on the command code.

@p function do_char:boolean;
label 9998,9999;
var o:eight_bits; {operation code of the current command}
@!p,@!q:integer; {parameters of the current command}
begin {we've already scanned the |boc|}
do_char←true;
while true do @<Translate the next command in the \.{GF} file;
		|goto 9999| if it was |eoc|;
		|goto 9998| if premature termination is needed@>;
9998: print_ln('!'); do_char←false;
9999: end;

@ @d show_label(#)==print(a:1,': ',#)
@d show_mnemonic(#)==if wants_mnemonics then begin print_nl; show_label(#); end
@d error(#)==begin show_label('! ',#); print_nl; end
@d start_op==a←cur_loc; o←get_byte; p←first_par(o);
	if eof(gf_file) then bad_gf('the file ended prematurely')
@.the file ended prematurely@>

@<Translate the next command...@>=
begin start_op;
@<Start translation of command |o| and |goto| the appropriate label to
	finish the job@>;
end

@ The multiway switch in |first_par|, above, was organized by the length
of each command; the one in |do_char| is organized by the semantics.

@<Start translation...@>=
if o≤paint1+3 then @<Translate a sequence of |paint| commands,
	until reaching a non-|paint|@>;
if (new_row≤o) and (o≤right_z_83) then
	@<Translate a |new_row|, |right| or |left| command@>
else case o of
	three_cases(skip1): @<Translate a |skip| command@>;
	@t\4@>@<Cases for commands |nop|, |pre|, |post|, |post_post|, |boc|,
		and |eoc|@>@;
	four_cases(xxx1): @<Translate an |xxx| command@>;
	yyy: @<Translate a |yyy| command@>;
	othercases error('undefined command ',o:1,'!')
@.undefined command@>
	endcases

@ @<Cases for commands |nop|...@>=
nop: show_mnemonic('nop');
pre: begin error('preamble command within a character!'); goto 9998;
	end;
@.preamble command within a page@>
post,post_post: begin error('postamble command within a character!');
@.postamble command within a page@>
	goto 9998;
	end;
boc: begin error('boc occurred before eoc!'); goto 9998;
@.boc occurred before eoc@>
	end;
eoc: begin show_mnemonic('eoc');
	print_nl; goto 9999;
	end;

@ @<Translate an |xxx| command@>=
begin show_mnemonic('xxx '''); bad_char←false; n←16;
if p<0 then error('string of negative length!');
@.string of negative length@>
while p>0 do
	begin q←get_byte;
	if (q<" ")∨(q>"~") then bad_char←true;
	if wants_mnemonics then
		begin print(xchr[q]);
		if n<line_length then incr(n)
		else	begin print_nl; n←2;
			end;
		end;
	decr(p);
	end;
if wants_mnemonics then print('''');
if bad_char then error('non-ASCII character in xxx command!');
@.non-ASCII character...@>
end

@ @<Glob...@>=
@!bad_char:boolean; {has a non-ASCII character code appeared in this \\{xxx}?}

@ @<Translate a |yyy| command@>=
begin show_mnemonic('yyy ',p:1,' (');
if wants_mnemonics then
	begin print_scaled(p); print(')');
	end;
end

@ The bulk of a \.{GF} file generally consists of |paint| commands,
so we collect them together and print them in an abbreviated format
on one line.

@<Translate a sequence of |paint| commands...@>=
begin if wants_mnemonics then print(' paint ');
repeat @<Paint the next |p| pixels@>;
start_op;
until o>paint1+3;
end

@ @<Paint the next...@>=
if wants_mnemonics then
	if paint_switch=white then print('(',p:1,')')@+else print(p:1);
write(term_out,' p values= ',p:1);  {added for debugging}
if p>0 then
	begin if y>max_y_observed then max_y_observed←y;
	if y<min_y_observed then min_y_observed←y;
	l←x; r←x+p-1;
	if r>max_x_observed then max_x_observed←r;
	if l<min_x_observed then min_x_observed←l;
	if wants_pixels then
		@<Paint pixels |l| through |r| in row |y| of the subarray@>;
	x←r+1;
	end;
paint_switch←white+black-paint_switch
	{could also be |paint_switch←not paint_switch|}

@ @<Paint pixels |l| through |r| in row |y| of the subarray@>=
if y≤max_y then if y≥min_y then
	begin if l<min_x then l←min_x;
	if r>max_x then r←max_x;
	x←l;
	while x≤r do
		begin image←paint_switch; incr(x);
		end;
	end

@ @<Translate a |new_row|, |right| or |left| command@>=
begin show_mnemonic('newrow ',p:1);
decr(y); z←z+p; x←z; paint_switch←black;
if wants_mnemonics then print(' (y=',y:1,', z=',z:1,')');
end

@ @<Translate a |skip| command@>=
begin show_mnemonic('skip',o-skip1+1:1,' ',p:1);
y←y-(p+1); x←z; paint_switch←black;
if wants_mnemonics then print(' (y=',y:1,', z=',z:1,')');
end
@* Reading the postamble.
Now imagine that we are reading the \.{GF} file and positioned just
after the |post| command. That, in fact, is the situation,
when the following part of \.{GFtype} is called upon to read, translate,
and check the rest of the postamble.

@p procedure read_postamble;
var k:integer; {loop index}
@!p,@!q,@!m,@!v,@!w,@!c:integer; {general purpose registers}
begin post_loc←cur_loc-1;
print('Postamble starts at byte ',post_loc:1);
@.Postamble starts at byte n@>
if post_loc=gf_prev_ptr then print_ln('.')
else print_ln(', after special info at byte ',gf_prev_ptr:1,'.');
p←signed_quad;
if p≠gf_prev_ptr then
	error('backpointer in byte ',cur_loc-4:1,
		' should be ',gf_prev_ptr:1,' not ',p:1,'!');
@.backpointer...should be p@>
design_size←signed_quad; check_sum←signed_quad;@/
print('design size = ',design_size:1,' (');
print_scaled(design_size div 16); print_ln('pt)');
print_ln('check sum = ',check_sum:1);@/
hppp←signed_quad; vppp←signed_quad;@/
print('hppp = ',hppp:1,' ('); print_scaled(hppp); print_ln(')');
print('vppp = ',vppp:1,' ('); print_scaled(vppp); print_ln(')');
min_x_stated←signed_quad; max_x_stated←signed_quad;
min_y_stated←signed_quad; max_y_stated←signed_quad;@/
print_ln('min x = ',min_x_stated:1,', max x = ',max_x_stated:1);@/
if min_x_stated>min_x_overall then
	error('min x should be <=',min_x_overall:1,'!');
if max_x_stated<max_x_overall then
	error('max x should be >=',max_x_overall:1,'!');
print_ln('min y = ',min_y_stated:1,', max y = ',max_y_stated:1);@/
if min_y_stated>min_y_overall then
	error('min y should be <=',min_y_overall:1,'!');
if max_y_stated<max_y_overall then
	error('max y should be >=',max_y_overall:1,'!');
@<Process the character locations in the postamble@>;
@<Make sure that the end of the file is well-formed@>;
end;

@ @<Glob...@>=
@!design_size,@!check_sum: integer; {\.{TFM}-oriented parameters}
@!hppp, @!vppp: integer; {magnification-oriented parameters}
@!post_loc: integer; {location of the |post| command}

@ @<Set init...@>=
min_x_overall←max_int; max_x_overall←-max_int;
min_y_overall←max_int; max_y_overall←-max_int;

@ When we get to the present code, the |post_post| command has
just been read.

@<Make sure that the end of the file is well-formed@>=
if k≠post_post then
	error('should be postpost!');
@.should be postpost@>
q←signed_quad;
if q≠post_loc then
	error('postamble pointer should be ',post_loc:1,' not ',q:1);
@.postamble pointer should be...@>
m←get_byte;
if m≠gf_id_byte then error('identification byte should be ',gf_id_byte:1);
@.identification byte should be n@>
k←cur_loc; m←223;
while (m=223)∧ not eof(gf_file) do m←get_byte;
if not eof(gf_file) then bad_gf('signature in byte ',cur_loc-1:1,
@.signature...should be...@>
		' should be 223')
else if cur_loc<k+4 then
	error('not enough signature bytes at end of file!');
@.not enough signature bytes...@>

@ @<Process the character locations...@>=
repeat k←get_byte;
if k=char_loc then
	begin c←first_par(char_loc);
	v←signed_quad; w←signed_quad; p←signed_quad;
	if wants_mnemonics then
		begin print('Character ',c:1,': device width ',v:1,', width ',w:1,' (');
		print_scaled(w div 16);
		print_ln('ds), location ',p:1);
		end;
	if p≠char_ptr[c] then
		error('character location should be ',char_ptr[c]:1,'!');
@.character location should be...@>
	k←nop;
	end;
until k≠nop;
@* The main program.
Now we are ready to put it all together. This is where \.{GFtype} starts,
and where it ends.

@p begin initialize; {get all variables initialized}
dialog; {set up all the options}
@<Process the preamble@>;
@<Translate all the characters@>;
print_nl;
read_postamble;
print('The file had ',total_chars:1,' character');
if total_chars≠1 then print('s');
print(' altogether.');
@.Font had n characters...@>
final_end:end.

@ The main program needs a few global variables in order to do its work.

@<Glob...@>=
@!a:integer; {byte number of the current command}
@!c,@!l,@!m,@!n,@!o,@!p,@!q,@!r:integer; {general purpose registers}

@ \.{GFtype} looks at the preamble in order to do error checking, and to
display the introductory comment.

@<Process the preamble@>=
open_gf_file;
o←get_byte; {fetch the first byte}
if o≠pre then bad_gf('First byte isn''t start of preamble!');
@.First byte isn't...@>
o←get_byte; {fetch the identification byte}
if o≠gf_id_byte then
	error('identification byte should be ',gf_id_byte:1,
	' not ',o:1,'!');
@.identification byte should be n@>
o←get_byte; {fetch the length of the introductory comment}
print('''');
while o>0 do
	begin decr(o); print(xchr[get_byte]);
	end;
print_ln('''');

@ @<Translate all...@>=
repeat gf_prev_ptr←cur_loc;
	@<Pass |nop|, |xxx| and |yyy| commands@>;
	if o≠post then
		begin if o≠boc then
			bad_gf('byte ',cur_loc-1:1,' is not boc (',o:1,')');
@.byte n is not boc@>
		print_nl; print(cur_loc-1:1,': beginning of char ');
		@<Pass a |boc| command@>;
		if not do_char then bad_gf('char ended unexpectedly');
@.char ended unexpectedly@>
		@<Pass an |eoc| command@>;
		if wants_pixels then @<Print the image@>;
		end;
until o=post;

@ @<Pass |nop|, |xxx| and |yyy| commands@>=
repeat start_op;
	if o=yyy then
		begin @<Translate a |yyy|...@>; o←nop;
		end
	else if (o≥xxx1) and (o≤xxx1+3) then
		begin @<Translate an |xxx|...@>; o←nop;
		end
	else if o=nop then show_mnemonic('nop');
until o≠nop;

@ @<Pass a |boc|...@>=
a←cur_loc;
incr(total_chars);
character_code←signed_quad;
p←signed_quad;
c←character_code mod 256;
if c<0 then c←c+256;
print(c:1);
if character_code≠c then
	print(' in family ',(character_code-c) div 256 : 1);
min_x_stated←signed_quad; max_x_stated←signed_quad;
min_y_stated←signed_quad; max_y_stated←signed_quad;
z←signed_quad;
if wants_mnemonics then
	print_ln(': ',min_x_stated:1,'<=x<',max_x_stated+1:1,' ',
	 min_y_stated:1,'<=y<',max_y_stated+1:1);
min_x_observed←max_int; max_x_observed←-max_int;
min_y_observed←max_int; max_y_observed←-max_int;
if char_ptr[c]≠p then
	error('previous character pointer should be ',char_ptr[c]:1,
		', not ',p:1,'!')
@.previous character pointer...@>
else if p>0 then if wants_mnemonics then
	print_ln('(previous character with the same code started at byte ',
		p:1,')');
char_ptr[c]←gf_prev_ptr;
if wants_mnemonics then print('(initially y=',y:1,', z=',z:1,')');
if wants_pixels then @<Clear the image@>;
y←max_y_stated;
x←z;
paint_switch←black;

@ @<Pass an |eoc|...@>=
if min_x_observed<min_x_overall then min_x_overall←min_x_observed;
if max_x_observed>max_x_overall then max_x_overall←max_x_observed;
if min_y_observed<min_y_overall then min_y_overall←min_y_observed;
if max_y_observed>max_y_overall then max_y_overall←max_y_observed;
if min_x_observed<min_x_stated then
	print_ln('The previous character should have had min x <= ',
		min_x_observed:1);
if max_x_observed>max_x_stated then
	print_ln('The previous character should have had max x >= ',
		max_x_observed+1:1);
if min_y_observed<min_y_stated then
	print_ln('The previous character should have had min y <= ',
		min_y_observed:1);
if max_y_observed>max_y_stated then
	print_ln('The previous character should have had max y >= ',
		max_y_observed+1:1);
@* System-dependent changes.
This section should be replaced, if necessary, by changes to the program
that are necessary to make \.{GFtype} work at a particular installation.
It is usually best to design your change file so that all changes to
previous sections preserve the section numbering; then everybody's version
will be consistent with the printed program. More extensive changes,
which introduce new sections, can be inserted here; then only the index
itself will get a new section number.
@↑system dependencies@>
@* Index.
Pointers to error messages appear here together with the section numbers
where each ident\-i\-fier is used.